#!/usr/bin/php
<?php
/*
	build script for myTinyTodo
	
	usage: build.php target_folder
	
	Licensed under the GNU GPL v3 license. See file src/COPYRIGHT for details.
*/ 

function copydir($src,$dst,$mode=0755) { 
    $dir = opendir($src); 
    @mkdir($dst); 
    while(false !== ( $file = readdir($dir)) ) { 
        if (( $file != '.' ) && ( $file != '..' )) { 
            if ( is_dir($src . '/' . $file) ) { 
                copydir($src . '/' . $file,$dst . '/' . $file); 
            } 
            else { 
                copy($src . '/' . $file,$dst . '/' . $file); 
            } 
        } 
    } 
    closedir($dir); 
} 

function create_zip($archive_name, $archive_folder) {
	$pathlen = strlen($archive_folder)-strlen(basename($archive_folder));
	//print $pathlen." ".substr($archive_folder, $pathlen);
	$zip = new ZipArchive; 
	if ($zip -> open($archive_name, ZipArchive::CREATE) === TRUE) 
	{ 
		$dir = preg_replace('/[\/]{2,}/', '/', $archive_folder."/"); 
    
		$dirs = array($dir); 
		while (count($dirs)) 
		{ 
			$dir = current($dirs); 
			$zip -> addEmptyDir(substr($dir,$pathlen));
			print "add: ".substr($dir,$pathlen)."\n";
			$dh = opendir($dir); 
			while($file = readdir($dh)) 
			{ 
				if ($file != '.' && $file != '..') 
				{ 
					if (is_file($dir.$file))  {
						//print "add: ".substr($dir.$file,$pathlen)."\n";
						$zip->addFile($dir.$file, substr($dir.$file,$pathlen));
					} elseif (is_dir($dir.$file)) {
						$dirs[] = $dir.$file."/"; 
					}
				} 
			} 
			closedir($dh); 
			array_shift($dirs); 
		}     
		return $zip->close();
	} else { 
		return False;
	} 
}


if ($argc<2 || !is_dir($dest = $argv[1]) || !is_writeable($dest))
 die("usage: build.php target_folder\n");

$base = dirname(__file__);
$src = "$base/src";
$build = "$dest/mytinytodo";

// copy the source
copydir($src, $build);

// make sure we won't overwrite config and settings when unzipping
// this over an existing installation
@unlink("$build/db/config.php");
@unlink("$build/db/todolist.db");

// replace @VERSION in themes/default/index.php, setup.php
$version = trim(file_get_contents("$base/version.txt"));
foreach(array('themes/default/index.php', 'setup.php') as $file) {
	$file="$build/$file";
	$content=str_replace("@VERSION", $version,file_get_contents($file));
	file_put_contents($file, $content);
}

// create zip file
create_zip("$dest/myTinyTodo-$version.zip", $build);
